package com.wt.hrentSystem.common.util;

import org.yaml.snakeyaml.Yaml;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class YmlUtil {

    private static Map<String, LinkedHashMap> ymls = new HashMap<>();

    private static ThreadLocal<String> nowFileName = new ThreadLocal<>();

    public static void loadYml(String fileName) {
        nowFileName.set(fileName);
        if (!ymls.containsKey(fileName)) {
            ymls.put(fileName, new Yaml().loadAs(YmlUtil.class.getResourceAsStream("/" + fileName), LinkedHashMap.class));
        }
    }

    public static Object getValue(String key){
        String[] keys = key.split("[.]");

        Map ymlInfo = (Map) ymls.get(nowFileName.get()).clone();
        for (int i = 0; i < keys.length; i++) {
            Object value = ymlInfo.get(keys[i]);
            if (i < keys.length - 1) {
                ymlInfo = (Map) value;
            } else if (value == null) {
                try {
                    throw new Exception("key不存在");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                return value;
            }
        }
        throw new RuntimeException("空文件");
    }

    public static Object value(String key) throws Exception {
        loadYml("application.yml");
        return getValue(key);
    }
}

